import { GameMgr } from "../GameMgr";
import { Player } from "./Player";
import { Point } from "./Point";
import Utils from "../GameUtils";

export class Small {

    gameMgr:GameMgr
    player:Player
    point:Point

    is_ready:Boolean = false            //小子相当于就是将军，在他的回合行动几次都行
    energy:number = 0                   //能量
    updateTimeout: NodeJS.Timeout       //通知客户端更新大子数据延迟器，防止多个地方同时调用update

    constructor(gameMgr:GameMgr,player:Player,point:Point) {
        this.gameMgr = gameMgr
        this.player = player
        this.point = point
        this.point.small  = this
    }

    gc() {
        this.gameMgr = null
        this.player = null
        this.point = null
        clearTimeout(this.updateTimeout)
    }

    toObj() {
        let obj = {
            "point_id":this.point.id,
            "is_ready":this.is_ready,
            "energy":this.energy
        }
        return obj
    }

    /** 通知客户端刷新数据 */
    update() {
        clearTimeout(this.updateTimeout)
        this.updateTimeout = setTimeout(()=>{
            if (this.gameMgr != null) {
                this.gameMgr.sendBroadcast(Utils.getObj("update_small",{"small":this.toObj()},true,false),false)
            }
        },20)
    }

    die(murderer:Player) {
        this.gameMgr.sendBroadcast(Utils.getObj("small_die",{"point_id":this.point.id}))
        if (this.player != murderer) {
            //击杀者获得将令
        }
        this.point.small = null
        this.player.is_death = true
        this.player.arr_bigs.forEach(big => {
            big.die(murderer)
        });
        this.gameMgr.switchTurnPlayer(this.player)
        this.gameMgr.checkAlive()
    }

    turnOver() {
        this.is_ready = false
        this.energy = 0
        this.update()
    }

    turnStart() {
        this.is_ready = true
        this.energy += 6
        this.update()
    }

    
    changeEnergy(num: number) {
        this.energy += num
        this.update()
    }
}